﻿using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;
using System.Threading.Channels;

var connFactory = new ConnectionFactory();
connFactory.HostName = "127.0.0.1";
connFactory.DispatchConsumersAsync = true;
string exChangeName = "exchange1"; //交换机名字
var connection = connFactory.CreateConnection(); //创建TCP


string queueName = "queue1";
string routintgKey = "key1";
using (var channel = connection.CreateModel()) {  //信道
    channel.ExchangeDeclare(exChangeName, "direct"); //申明交换机
    channel.QueueDeclare(queue:queueName, durable: true, exclusive: false, autoDelete: false, arguments: null); //队列
    channel.QueueBind(queue: queueName, exChangeName, routintgKey);


    AsyncEventingBasicConsumer consumer = new AsyncEventingBasicConsumer(channel);
    consumer.Received += Consumer_Received;
    channel.BasicConsume(queueName, autoAck: false, consumer: consumer);
    Console.WriteLine("按回车才退出");
    Console.ReadLine();
    async Task Consumer_Received(object sender,BasicDeliverEventArgs _event)
    {
        try
        {
            byte[] bytes= _event.Body.ToArray();
            string text = Encoding.UTF8.GetString(bytes);
            Console.WriteLine($"{DateTime.Now}收到消息:" + text);
            // DeliveryTag就是消息的编号
            channel.BasicAck(_event.DeliveryTag, multiple: false);
            await Task.Delay(800);
        }
        catch (Exception ex)
        {
            channel.BasicReject(_event.DeliveryTag, true); // 消息重发
            Console.WriteLine("异常：" + ex.ToString());
        }

    }
}



